import 'package:buttons_tabbar/buttons_tabbar.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/controller/register.dart';
import 'package:ichinesereader/models/forms/forms.dart';
import 'package:ichinesereader/models/register/SchoolUserInfo.dart';
import 'package:ichinesereader/models/register/paymentUserInfo.dart';
import 'package:ichinesereader/themes/appTheme.dart';
import 'package:ichinesereader/widgets/dialogs/simpleAlertDialog.dart';
import 'package:reactive_file_picker/reactive_file_picker.dart';
import 'package:reactive_forms/reactive_forms.dart';
import '../common/paymentForWeb.dart';

late TabController billingTab;

class BillingForSchool extends StatefulWidget {
  BillingForSchool({Key? key, required this.id, this.quoteNumber})
      : super(key: key);
  final String id;
  final String? quoteNumber;

  @override
  State<BillingForSchool> createState() => _BillingForSchool();
}

class _BillingForSchool extends State<BillingForSchool>
    with SingleTickerProviderStateMixin {
  final RegisterController _registerController = new RegisterController();
  SchoolUserInfoPayment _userInfo = new SchoolUserInfoPayment();
  bool _loadWebview = false;
  final PurchaseForm formModel1 = new PurchaseForm();
  final PurchaseForm formModel2 = new PurchaseForm();
  late FormGroup form1;
  late FormGroup form2;

  @override
  void initState() {
    billingTab = TabController(vsync: this, length: 3);
    _registerController.getPaymentReocord(widget.id).then((res) {
      var status = res.status;
      setState(() {
        _userInfo = res;
      });
      switch (status) {
        case 'Unpaid':
          setBraintree();
          break;
        case 'Failed':
          setBraintree();
          showGeneralDialog(
              context: context,
              transitionDuration: Duration(milliseconds: 0),
              pageBuilder: (bc, ania, anis) {
                return SimpleAlertDialog(
                  title: "Failed",
                  message:
                      "Your documents are declined, Please check and resubmit or you can choose other payment methods.",
                );
              });
          break;
        case 'Pending':
          showGeneralDialog(
              context: context,
              transitionDuration: Duration(milliseconds: 0),
              pageBuilder: (bc, ania, anis) {
                return SimpleAlertDialog(
                  title: "Pending",
                  message:
                      "It will take at least 24 hours to verify the transaction",
                );
              });
          break;
        case 'Paid':
          break;

        case 'Complete':
          showGeneralDialog(
              context: context,
              transitionDuration: Duration(milliseconds: 0),
              pageBuilder: (bc, ania, anis) {
                return SimpleAlertDialog(
                  title: "Completed",
                  message:
                      "Congratulations, you have already finished the applicaton process.",
                );
              });
          break;
      }
    });

    // if (controller.currentLevel.value.indexOf("HSK") > 0) {
    //   _levelOptions = Constants.hskEvaluationOptions;
    // } else if (controller.currentLevel.value.indexOf(RegExp(r'\d')) < 0) {
    //   _levelOptions = Constants.actflEvaluationOptions;
    // }
    form1 = formModel1.form;
    form2 = formModel2.form;
    form1.control("paymentText").value = "";
    form1.control("paymentFile").value = const MultiFile<String>(
      platformFiles: [],
    );
    form2.control("paymentText").value = "";
    form2.control("paymentFile").value = const MultiFile<String>(
      platformFiles: [],
    );
    super.initState();
  }

  _buildForm1() {
    List<Widget> formWidget = [];

    formWidget.add(ReactiveTextField(
      formControlName: 'paymentText',
      style: TextStyle(
          fontSize: 15.0,
          fontFamily: 'Montserrat',
          color: Get.isDarkMode ? Colors.white : Colors.black),
      textInputAction: TextInputAction.next,
      decoration: InputDecoration(
        alignLabelWithHint: true,
        labelText: 'PO Number'.tr,
        labelStyle: TextStyle(
            fontFamily: 'Montserrat',
            color: Get.isDarkMode ? Get.theme.primaryColorLight : Colors.black),
      ),
    ));
    formWidget.add(SizedBox(height: 20));
    formWidget.add(ReactiveFilePicker<String>(
      formControlName: 'paymentFile',
      decoration: const InputDecoration(
        labelText: 'PO File',
        border: OutlineInputBorder(),
        helperText: '',
      ),
      filePickerBuilder: (pickImage, files, onChange) {
        final items = [
          ...files.platformFiles
              .asMap()
              .map((key, value) => MapEntry(
                    key,
                    ListTile(
                      onTap: () {
                        onChange(files.copyWith(
                            files: List<String>.from(files.files)
                              ..removeAt(key)));
                      },
                      leading: const Icon(Icons.delete),
                      title: PlatformFileListItem(value).build(context),
                    ),
                  ))
              .values,
        ];
        return Column(
          children: [
            SizedBox(
              height: 10,
              width: 20,
              child: ListView.builder(
                itemCount: items.length,
                itemBuilder: (_, i) {
                  return items[i];
                },
              ),
            ),
            ElevatedButton(
              onPressed: pickImage,
              child: const Text("Upload file"),
            ),
          ],
        );
      },
    ));

    return formWidget;
  }

  _buildForm2() {
    List<Widget> formWidget = [];

    formWidget.add(ReactiveTextField(
      formControlName: 'paymentText',
      style: TextStyle(
          fontSize: 15.0,
          fontFamily: 'Montserrat',
          color: Get.isDarkMode ? Colors.white : Colors.black),
      textInputAction: TextInputAction.next,
      decoration: InputDecoration(
        alignLabelWithHint: true,
        labelText: 'Bank Name'.tr,
        labelStyle: TextStyle(
            fontFamily: 'Montserrat',
            color: Get.isDarkMode ? Get.theme.primaryColorLight : Colors.black),
      ),
    ));
    formWidget.add(SizedBox(height: 20));
    formWidget.add(ReactiveFilePicker<String>(
      formControlName: 'paymentFile',
      decoration: const InputDecoration(
        labelText: 'Transaction File',
        border: OutlineInputBorder(),
        helperText: '',
      ),
      filePickerBuilder: (pickImage, files, onChange) {
        final items = [
          ...files.platformFiles
              .asMap()
              .map((key, value) => MapEntry(
                    key,
                    ListTile(
                      onTap: () {
                        onChange(files.copyWith(
                            files: List<String>.from(files.files)
                              ..removeAt(key)));
                      },
                      leading: const Icon(Icons.delete),
                      title: PlatformFileListItem(value).build(context),
                    ),
                  ))
              .values,
        ];
        return Column(
          children: [
            SizedBox(
              height: 10,
              width: 20,
              child: ListView.builder(
                itemCount: items.length,
                itemBuilder: (_, i) {
                  return items[i];
                },
              ),
            ),
            ElevatedButton(
              onPressed: pickImage,
              child: const Text("Upload file"),
            ),
          ],
        );
      },
    ));

    return formWidget;
  }

  setBraintree() {
    PaymentUserInfo formData = new PaymentUserInfo();
    formData.firstName = _userInfo.firstName;
    formData.lastName = _userInfo.lastName;
    formData.email = _userInfo.email;
    formData.braintreeCustomerId = _userInfo.braintreeCustomerId;
    _registerController.getPaymentToken(formData).then((value) {
      setState(() {
        _loadWebview = true;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Theme.of(context).colorScheme.onInverseSurface,
        appBar: AppBar(
          title: Text("Payment".tr),
          leading: BackButton(onPressed: () {
            Navigator.of(context).pop();
          }),
        ),
        body: Container(
            margin: EdgeInsets.all(10),
            alignment: Alignment.center,
            child:
                Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              Center(
                child: Text(
                    "Your quote number is ${widget.quoteNumber},please save this number"),
              ),
              ButtonsTabBar(
                controller: billingTab,
                radius: 3.0,
                backgroundColor: AppTheme.colors.orangeBtn,
                contentPadding: EdgeInsets.symmetric(horizontal: 12.0),
                tabs: [
                  Tab(text: 'Credit Card'),
                  Tab(text: 'Purchase Order'),
                  Tab(text: 'Wire Transfer'),
                ],
              ),
              Expanded(
                child: TabBarView(
                  controller: billingTab,
                  children: [
                    SafeArea(
                      child: SizedBox(
                        height: 460.0,
                        child: _loadWebview ? PaymentFoWebWebview() : Text(""),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(36, 18, 36, 18),
                      child: ReactiveForm(
                        formGroup: form1,
                        child: Column(
                          children: _buildForm1(),
                        ),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(36, 18, 36, 18),
                      child: ReactiveForm(
                        formGroup: form2,
                        child: Column(
                          children: _buildForm2(),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  TextButton(
                    child: Text('Back'.tr,
                        style: TextStyle(
                            fontSize: 20, fontWeight: FontWeight.w500)),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                  TextButton(
                    child: Text('Pay'.tr,
                        style: TextStyle(
                            fontSize: 20, fontWeight: FontWeight.w500)),
                    onPressed: () {},
                  ),
                  // const SizedBox(width: 8),
                ],
              ),
            ])));
  }
}

abstract class ListItem {
  Widget build(BuildContext context);
}

class PlatformFileListItem extends ListItem {
  final PlatformFile platformFile;

  PlatformFileListItem(this.platformFile);

  @override
  Widget build(context) {
    return Text(platformFile.path ?? '');
  }
}
